package com.ly.jvm.oom.memoryleak.threadlocal;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Classname ThreadLocalMemoryLeak
 * @Description TODO
 * @Date 2020/12/29 21:35
 * @Author 冷心影翼
 */
public class ThreadLocalMemoryLeak {

    ThreadLocal<Map<String,byte[]>> threadLocal = new ThreadLocal<>();

    public void serviceA() {
        for (int i = 0; i < 8; i++) {
            new Thread(()->{
                setMap();
                serviceB();
                threadLocal = null;
                try {
                    TimeUnit.SECONDS.sleep(60);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }

        while (true) {

        }
    }

    public void setMap() {
        HashMap<String,byte[]> hashMap = new HashMap<>();
        hashMap.put(Thread.currentThread().getId()+"",new byte[1024*1024*10]);
        threadLocal.set(hashMap);
    }

    public void serviceB() {
//        Map<String, byte[]> stringMap = threadLocal.get();
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getId());
    }

    public static void main(String[] args) {
        ThreadLocalMemoryLeak threadLocalMemoryLeak = new ThreadLocalMemoryLeak();
        threadLocalMemoryLeak.serviceA();
    }
}
